<script setup lang="ts">
import type {
  SysMenuTreeVo,
} from '#/system/menu'
import type {
  SysTenantPackageQo,
} from '#/system/tenants/tenantsPackage'
import type {
  TreeInstance,
} from 'element-plus'
import {
  createSysTenantPackageApi,
  getSysTenantPackageDetailsApi,
  updateSysTenantPackageApi,
} from '@/api/system/tenants/tenantsPackage'
import {
  getTreeAllIds,
} from '@/utils/tree'

interface OnCloseResolveType extends CloseResolveType {}
let onCloseResolve = function (_value: OnCloseResolveType) { }

const dialogRef = $ref<DialogInstance>()
const ruleFormRef = ref<FormInstance>()

let dialogModal = $ref<SysTenantPackageQo>({})
let dialogAction = $ref<DialogAction>('add')
let confirmLoading = $ref(false)
let dialogLoading = $ref(false)
let menuTree = $ref<SysMenuTreeVo[]>([])

const treeRef = $ref<TreeInstance>()
const rules = reactive<FormRules<SysTenantPackageQo>>({
  name: [
    { required: true, message: '租户套餐名称不能为空', trigger: 'blur' },
  ],
})
let treeIds = $ref<string[]>([])

let isSelectAll = $ref(false)
let isLinkage = $ref(false)

async function getDefaultModel() {
  return {} as SysTenantPackageQo
}
// 打开
async function showDialog(args: {
  title: string
  action?: DialogAction
  model: {
    id?: string
  }
  menuTree: SysMenuTreeVo[]
}) {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: args.title,
  })

  menuTree = args.menuTree
  treeRef?.setCheckedKeys([])
  ruleFormRef.value?.clearValidate()
  onCloseResolve = dialogRes.onCloseResolve

  dialogAction = args.action ?? 'add'

  if (args.model.id) {
    dialogModal.id = args.model.id
  }

  if (args.action === 'add') {
    const defaultModel = await getDefaultModel()
    dialogModal = {
      ...defaultModel,
      ...args.model,
    }
  }
  else if (args.action === 'edit' || args.action === 'views') {
    await reflash()
  }

  return await dialogRes.dialogPrm
}

async function reflash() {
  if (!dialogModal.id)
    return
  dialogLoading = true
  const res = await getSysTenantPackageDetailsApi(dialogModal.id)
  if (!res)
    return
  dialogLoading = false
  Object.assign(dialogModal, res.data)
  treeIds = getTreeAllIds(menuTree)
  isSelectAll = false
  isLinkage = false
}

// 确认
async function confirm(formEl: FormInstance | undefined) {
  if (!formEl)
    return
  await formEl.validate(async (valid) => {
    if (!valid) {
      return
    }
    confirmLoading = true

    // 获取当前选中菜单
    if (treeRef) {
      const menuIds = treeRef.getCheckedNodes(false, true).map((item: SysMenuTreeVo) => item.id)
      dialogModal.menuIds = menuIds as string[]
    }

    if (dialogAction === 'add') {
      await createSysTenantPackageApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    else if (dialogAction === 'edit') {
      await updateSysTenantPackageApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    confirmLoading = false
    Message({
      type: 'success',
      message: `${DialogActionMap[dialogAction as DialogAction]}成功`,
    })
    onCloseResolve({ type: true })
  })
}

// 取消
function cancel() {
  ruleFormRef.value?.clearValidate()
  onCloseResolve({ type: false })
}

watch(() => isSelectAll, () => {
  if (!treeRef)
    return
  isSelectAll
    ? treeRef.setCheckedKeys(treeIds, false)
    : treeRef.setCheckedKeys([])
})

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    :before-close="cancel"
    :hide-confirm="dialogAction === 'views'"
    :confirm-loading="confirmLoading"
    :disabled-confirm="dialogLoading"
    @confirm="confirm(ruleFormRef)"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="dialogLoading"
      :model="dialogModal"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="dialogModal.name"
          placeholder="请输入租户套餐名称"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="dialogModal.remark"
          type="textarea"
          placeholder="请输入备注"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="菜单权限">
        <div un-w-full>
          <div>
            <el-checkbox v-model="isSelectAll" label="全选/全不选" />
            <el-checkbox v-model="isLinkage" label="父子联动" />
          </div>
          <el-tree
            ref="treeRef"
            :data="menuTree"
            :props="{
              label: 'title',
            }"
            class="menu-tree"
            node-key="id"
            show-checkbox
            :check-strictly="!isLinkage"
            :default-expanded-keys="dialogModal.menuIds"
            :disabled="dialogAction === 'views'"
            :default-checked-keys="dialogModal.menuIds"
          />
        </div>
      </el-form-item>
    </el-form>
  </sy-dialog>
</template>

<style scoped>
.menu-tree {
  border: 1px solid var(--sy-layout-bg-color);
}
</style>
